package com.forlove.app.common.base.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import com.forlove.app.ForloveApplication;
import com.forlove.app.R;
import com.forlove.app.common.base.CommonAppliction;
import com.forlove.app.common.base.event.BaseMessageEvent;
import com.forlove.app.common.base.mvp.presenter.IBasePresenter;
import com.forlove.app.common.base.mvp.view.BaseView;
import com.forlove.app.common.utils.CommonUtil;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.qselect.MainActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import cn.magicwindow.MLinkAPIFactory;
import cn.magicwindow.Session;


/**
 * Created by yx on 2017/6/2.
 */

public abstract class BaseActivity<T extends IBasePresenter> extends AppCompatActivity implements BaseView {

    /**
     * activity 是否处于前台
     */
    private boolean mShowing;

    public abstract int getLayoutId();

    protected T presenter;
    private long deltaTime = 0;
    private boolean canBack = true;
    //    private YimeiToast yimeiToast;
//
//    private YimeiLoadingDialog loadingDialog;
    protected Handler mHandler;

    public void initView() {

    }

    public void setPresenter(T presenter) {
        this.presenter = presenter;
    }

    protected void setCanBack(boolean canBack) {
        this.canBack = canBack;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //设置全屏
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (getLayoutId() != 0) {
            setContentView(getLayoutId());
            ButterKnife.bind(this);
            CommonAppliction.getInstance().addActivitys(this);
        }
        try {
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
        } catch (Exception e) {
            LogUtil.e("yjl", e.getMessage());
        }
        if (mHandler == null) {
            mHandler = new Handler(Looper.getMainLooper());
        }

        initView();
    }

    /**
     * 隐藏toolbar的原生的title
     */
    public void showToolBar(Toolbar toolbar, boolean showBack) {
        if (toolbar == null) {
            return;
        }
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();

        if (showBack) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            toolbar.setNavigationIcon(this.getResources().getDrawable(R.mipmap.tab_backarrow_gray));
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onBackPressed();
                }
            });
            actionBar.setDisplayShowTitleEnabled(false);
        } else {
            actionBar.setDisplayHomeAsUpEnabled(false);
            toolbar.setNavigationIcon(null);
            toolbar.setNavigationOnClickListener(null);
        }

        if (actionBar != null) {

//            actionBar.setDisplayShowTitleEnabled(false);
        }
    }

    /**
     * 显示右边的icon和点击事件
     */
    public void showToolBar(final BaseActivity baseActivity, Toolbar toolbar, int navigationIconID,
                            View.OnClickListener onClickListener, Toolbar.OnMenuItemClickListener onMenuItemClickListener) {
        if (toolbar == null && !(baseActivity instanceof BaseActivity)) {
            return;
        }

        baseActivity.setSupportActionBar(toolbar);
        ActionBar actionBar = baseActivity.getSupportActionBar();
        if (navigationIconID > 0) {
            actionBar.setDisplayHomeAsUpEnabled(true);

            toolbar.setOnMenuItemClickListener(onMenuItemClickListener);
            toolbar.setNavigationIcon(navigationIconID);
            toolbar.setNavigationOnClickListener(onClickListener);

        } else {
            //设置是否显示navigation
            actionBar.setDisplayHomeAsUpEnabled(false);
            toolbar.setNavigationIcon(null);
            toolbar.setNavigationOnClickListener(null);
        }

        if (actionBar != null) {
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mShowing = true;
        Uri mLink = getIntent().getData();
        if (mLink != null) {
            MLinkAPIFactory.createAPI(this).router(mLink);
        } else {
            MLinkAPIFactory.createAPI(this).checkYYB();
        }
    }

    @Override
    protected void onResume() {
        Session.onResume(this);
        super.onResume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mShowing = false;
    }


    @Override
    protected void onPause() {
        Session.onPause(this);
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        CommonAppliction.getInstance().removeActivity(this);
//        if (yimeiToast != null) {
//            yimeiToast.dismiss();
//            yimeiToast = null;
//        }
//        if (loadingDialog != null) {
//            loadingDialog.dismiss();
//            loadingDialog = null;
//        }
        presenter = null;
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        super.onDestroy();
    }

    /**
     * 只展示消息，并自动消失
     *
     * @param msg
     */
    protected void showToast(final String msg) {
//        if (yimeiToast == null) {
//            yimeiToast = new YimeiToast(this);
//        }
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                yimeiToast.setMsg(msg);
//                yimeiToast.show(true);
//            }
//        });
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                ToastUtils.toast(msg);
//            }
//        });


    }

    @Override
    public void onBackPressed() {
        if (!canBack) {
            if (System.currentTimeMillis() - deltaTime > 2000) {
                deltaTime = System.currentTimeMillis();
                Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show();
                return;
            }
            ForloveApplication.getInstance().exit();
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 展示消息，自动消失
     *
     * @param msg
     * @param success
     */
    protected void showToast(String msg, boolean success) {
        showToast(msg, success, true);
    }

    /**
     * 显示toast
     *
     * @param msg       文字说明
     * @param success   成功状态还是失败状态
     * @param isDismiss 是否自动消失
     */
    protected void showToast(final String msg, final boolean success, final boolean isDismiss) {
//        if (yimeiToast == null) {
//            yimeiToast = new YimeiToast(this);
//        }
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                yimeiToast.setMsg(msg);
//                yimeiToast.setMsg(msg, success);
//                yimeiToast.show(isDismiss);
//            }
//        });

    }

    @Override
    public void overridePendingTransition(int enterAnim, int exitAnim) {
        super.overridePendingTransition(enterAnim, exitAnim);
    }


    @Override
    public void showLoadingView() {
        //显示加载view
        //if (isShowing()) {
//        if (loadingDialog == null) {
//            loadingDialog = new YimeiLoadingDialog(this);
//        }
//        loadingDialog.setDialogCancelable(false);
//
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                loadingDialog.show(false);
//            }
//        });
//        if (mHandler != null) {
//            mHandler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    if (loadingDialog != null) {
//                        loadingDialog.dismiss();
//                    }
//                }
//            }, 6 * 1000);
//        }
//        // }
    }


    protected void dismissLoadingView() {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                if (loadingDialog != null && loadingDialog.isShowing()) {
//                    loadingDialog.dismiss();
//                }
//            }
//        });
    }

    @Override
    public void hideLoadingView() {
//        if (mHandler != null) {
//            mHandler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    if (loadingDialog != null && loadingDialog.isShowing()) {
//                        loadingDialog.dismiss();
//                    }
//                }
//            }, 1000);
//        }
    }

    protected boolean isShowing() {
        return mShowing;
    }

    /**
     * 必须使用标记符。这表明要在UI线程中处理
     * 不论事件是在哪个线程中发布出来的，该事件处理函数都会在UI线程中执行。该方法可以用来更新UI，但是不能处理耗时操作
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false)
    public void onEventMainThread(final BaseMessageEvent event) {
        LogUtil.e(getClass().getSimpleName() + " onEventMainThread:" + event.eventId);
//
//        if (event != null && event.eventId == 10003) {
//            toLoginActivity();
////            LogUtil.e("yjl", getClass().getSimpleName() + "  romove event:" + event.eventId);
//            EventBus.getDefault().removeStickyEvent(event);
//        }
//        if (event != null && event.getEventName().equals("event_fail_toast")) {
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    showToast("网络开小差了~~");
//                    hideLoadingView();
//                }
//            });
//        }
//        if (event != null && event.eventId == 10008) {
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    if (event.getEventName() != null) {
//                        showToast(event.getEventName());
//                    }
//                    hideLoadingView();
//                }
//            });
//        }

    }

    /**
     * 必须使用标记符。这表明要在与发布线程相同的线程中处理
     * 该事件在哪个线程发布出来的，事件处理函数就会在这个线程中运行
     * ，也就是说发布事件和接收事件在同一个线程。
     * 在线程模型为PostThread的事件处理函数中尽量避免执行耗时操作，
     * 因为它会阻塞事件的传递，甚至有可能会引起ANR.
     */
    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onEvent(BaseMessageEvent event) {

    }

    /**
     * 必须使用标记符。这表明如果是在UI线程中发布，则在新线程中运行
     * 如果事件是在UI线程中发布出来的，那么该事件处理函数就会在新的线程中运行,
     * 如果事件本来就是子线程中发布出来的，
     * 那么该事件处理函数直接在发布事件的线程中执行。
     * 在此事件处理函数中禁止进行UI更新操作
     */
    @Subscribe(threadMode = ThreadMode.BACKGROUND, sticky = true)
    public void onEventBackgroundThread(BaseMessageEvent event) {

    }

    /**
     * 必须使用标记符。无论事件在哪个线程发布，该事件处理函数都会在新建的子线程中执行,禁止进行UI更新操作
     */
    @Subscribe(threadMode = ThreadMode.ASYNC, sticky = true)
    public void onEventAsync(BaseMessageEvent event) {

    }


    /***********************************************************************************************/
    /**
     * 打开新的Activity，向左滑入效果
     *
     * @param intent
     */
    public void toActivity(final Intent intent) {
        CommonUtil.toActivity(this, intent);
    }

    /**
     * 打开新的Activity
     *
     * @param intent
     * @param showAnimation
     */
    public void toActivity(final Intent intent, final boolean showAnimation) {
        CommonUtil.toActivity(this, intent, showAnimation);
    }

    /**
     * 打开新的Activity，向左滑入效果
     *
     * @param intent
     * @param requestCode
     */
    public void toActivity(final Intent intent, final int requestCode) {
        CommonUtil.toActivity(this, intent, requestCode);
    }

    /**
     * 打开新的Activity
     *
     * @param intent
     * @param requestCode
     * @param showAnimation
     */
    public void toActivity(final Intent intent, final int requestCode, final boolean showAnimation) {
        CommonUtil.toActivity(this, intent, requestCode, showAnimation);
    }
    //启动新Activity方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

//    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false)
//    protected void onEventToLogin(BaseMessageEvent event) {
//        if (event != null && event.eventId == 10003) {
//            toLoginActivity();
//            //   EventBus.getDefault().cancelEventDelivery(event);
//        }
//    }


    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public synchronized void toLoginActivity() {
//        if (SystemUtils.getTopActivity().contains("WelcomeActivity")
//                || SystemUtils.getTopActivity().contains("LoginActivity")) {
//            return;
//        }
//        try {
//            Intent intent = new Intent();
//            intent.setClass(this, Class.forName("com.yimei.app.splash.WelcomeActivity"));
//            //intent.setClass(this, Class.forName("com.yimei.app.activity.register.ui.LoginActivity"));
//            LogUtil.e("yjl", getClass().getSimpleName() + "====" + SystemUtils.getTopActivity());
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    showToast("请先登录");
//                }
//            });
//            toActivity(intent);
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
    }

    protected void toMainActivity(Bundle bundle, boolean clearTask) {
        toMainActivity(-1, -1, bundle, clearTask);
    }

    protected void toMainActivity(Bundle bundle) {
        toMainActivity(-1, -1, bundle, false);
    }

    /**
     * 只是跳转的main activity
     * 不做子页面切换
     */
    protected void toMainActivity() {
        toMainActivity(-1, -1, null, false);
    }

    protected void toMainActivity(boolean clearTask) {
        toMainActivity(-1, -1, null, clearTask);
    }

    /**
     * 跳转main activity的某个子页面
     *
     * @param pos
     */
    protected void toMainActivity(int pos) {
        toMainActivity(pos, -1, null, false);
    }


    protected void toMainActivity(int pos, Bundle bundle) {
        toMainActivity(pos, -1, bundle, false);
    }

    protected void toMainActivity(int pos, int childView) {
        toMainActivity(pos, childView, null, false);
    }

    protected void toMainActivity(int pos, int childView, boolean clearTask) {
        toMainActivity(pos, childView, null, clearTask);
    }

    /**
     * 跳转main activity
     * 可以切换子页面和 子页面的二级页面
     *
     * @param pos       子页面
     * @param childView 子页面的二级页面
     * @param bundle    参数
     * @param clearTask 是否清除栈内页面
     */
    protected void toMainActivity(int pos, int childView, Bundle bundle, boolean clearTask) {
        Intent intent = new Intent();
        if (bundle == null) {
            bundle = new Bundle();
        }
        if (pos >= 0) {
            bundle.putInt("position", pos);
        }
        if (pos == 0 && childView >= 0) {
            bundle.putInt("childView", childView);
        }
        if (clearTask) {
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtras(bundle);
//        LogUtil.e("yjl", getClass().getSimpleName());
        intent.setClass(this, MainActivity.class);
//        toActivity(intent, false);
        startActivity(intent);
    }
}
